package com.example.administrator.szb.activity.myyewu;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.bean.YWBQGLBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.QTLog;
import com.example.zhouwei.library.CustomPopWindow;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/11/27/027.
 */

public class YWXQActivity_save extends BaseActivity {
    public YWBQGLBean ywbqglBean;
    YWBQGLBean.DataBean dataBean;
    HashMap<Integer, YWBQGLBean.DataBean> data_map = new HashMap<>();
    BaseAdapter<YWBQGLBean.DataBean.NextBeanX> adapter_nextX;
    BaseAdapter<YWBQGLBean.DataBean.NextBeanX.NextBean> adapter_next;//弹窗adapter
    int id;
    @Bind(R.id.ywxq_no_image_fh)
    ImageView ywxqNoImageFh;
    @Bind(R.id.ywxq_no_text_title)
    TextView ywxqNoTextTitle;
    @Bind(R.id.ywxq_no_recyclerview)
    RecyclerView ywxqNoRecyclerview;
    @Bind(R.id.ywxq_no_edit_xgms)
    EditText ywxqNoEditXgms;
    @Bind(R.id.ywxq_no_text_zs)
    TextView ywxqNoTextZs;
    @Bind(R.id.ywxq_no_xgms)
    LinearLayout ywxqNoXgms;
    @Bind(R.id.ywxq_no_button_bc)
    Button ywxqNoButtonBc;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wyxq_activity);
        SampleApplicationLike.getActivitiesInstance().add(this);
        ButterKnife.bind(this);
        editListenter(ywxqNoEditXgms,ywxqNoTextZs);
        requestData();
    }

    private void requestData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId() + "");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, YWBQGLBean.class, URLAddress.URLBASE + URLAddress.URL_YWBQGL, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ywbqglBean = (YWBQGLBean) response;
                if (ywbqglBean.getResult() == 1) {
                    initRecyclerView();
                    if (ywbqglBean.getData().size() == 0) {
                        //startActivity(new Intent(YWGLYESActivity.this,YWGLNOActivity_new.class));
//                        finish();
                        //Toasts.show(YWXQActivity_save.this, "快去添加便签吧。。。", Toast.LENGTH_SHORT);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //startActivity(new Intent(YWXQActivity_save.this,YWGLNOActivity_new.class));
            }
        });
    }

    private void initRecyclerView() {
        for (int i = 0; i < ywbqglBean.getData().size(); i++) {
            data_map.put(ywbqglBean.getData().get(i).getId(), ywbqglBean.getData().get(i));
        }

        id = getIntent().getIntExtra("id", -1);
        dataBean = data_map.get(id);
        ywxqNoEditXgms.setText(dataBean.getDescribe());
        ywxqNoRecyclerview.setLayoutManager(new LinearLayoutManager(this));


        initAdapterX();

        ywxqNoRecyclerview.setAdapter(adapter_nextX);
    }

    private void initAdapterX() {
        adapter_nextX = new BaseAdapter<YWBQGLBean.DataBean.NextBeanX>(this,dataBean.getNext()) {
            @Override
            public void convert(int position, BaseViewHolder holder, YWBQGLBean.DataBean.NextBeanX nextBeanX) {
                ((TextView) holder.getView(R.id.ywxq_no_text_item)).setText(nextBeanX.getTitle());
                ((TextView)holder.getView(R.id.ywxq_no_text_info_item)).setText(""+nextBeanX.getIsYXZ());
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_ywxq_item;
            }
        };

        adapter_nextX.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onItemClick(View view, int position) {
                showPopupwindow(R.layout.view_popuwindow_ywxq,R.layout.wyxq_activity,position);
        }
        });
    }


    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow(int view_layout_id, int rootview_layout_id,int position) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);


//        /**
//         * 如果是单选业务类型就将下面的清除确定布局移除
//         */
//        if (businessBean_choose.getData().get(0).getType() == 2){
//            popwindow_view.findViewById(R.id.view_popuwindow_ll_ywxq).setVisibility(View.GONE);
//        }
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);
        //处理popWindow 显示内容
        handleListView(popwindow_view,position);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
        //显示PopupWindow

    }

   public void handleListView(View view, final int position_data){
       RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.view_popuwindow_recycler_ywxq);
       initAdapter(position_data);
       recyclerView.setLayoutManager(new LinearLayoutManager(this));
       recyclerView.setAdapter(adapter_next);


       Button cancelAll = view.findViewById(R.id.view_popuwindow_button_cancel);
       Button sure = view.findViewById(R.id.view_popuwindow_button_sure);

       cancelAll.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               for (int i = 0; i < dataBean.getNext().get(position_data).getNext().size(); i++) {
                   dataBean.getNext().get(position_data).getNext().get(i).setGenre(0);
               }

               adapter_next.notifyDataSetChanged();
               dataBean.getNext().get(position_data).setIsYXZ("");
               adapter_nextX.notifyDataSetChanged();
           }
       });

       sure.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

               popWindow.dissmiss();
           }
       });
   }

    private void initAdapter(final int position_data) {
        adapter_next = new BaseAdapter<YWBQGLBean.DataBean.NextBeanX.NextBean>(this,dataBean.getNext().get(position_data).getNext()) {
            @Override
            public void convert(final int position, BaseViewHolder holder, final YWBQGLBean.DataBean.NextBeanX.NextBean nextBean) {
                if (nextBean.getGenre() == 1){
                    ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(true);
                }else{
                    ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(false);
                }

                ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setEnabled(false);
                ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setClickable(false);

                ((TextView)holder.getView(R.id.ywxq_no_popuwindow_text_item)).setText(nextBean.getTitle());

                ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b){

                            for (int j=0;j<dataBean.getNext().get(position_data).getNext().size();j++){
                                if (position!=j&&dataBean.getNext().get(position_data).getNext().get(j).getIs_repeal()==1){
                                    dataBean.getNext().get(position_data).getNext().get(j).setGenre(0);
                                }
                            }


                            if (nextBean.getIs_repeal()==1){
                                QTLog.e("ssssss");
                                for (int i=0;i<dataBean.getNext().get(position_data).getNext().size();i++){
                                    dataBean.getNext().get(position_data).getNext().get(i).setGenre(0);
                                }

                            }
                            
                            
                            if (nextBean.getType() == 2){
                                for (int i = 0; i <  dataBean.getNext().get(position_data).getNext().size(); i++) {

                                    dataBean.getNext().get(position_data).getNext().get(i).setGenre(0);

                                }

                                dataBean.getNext().get(position_data).getNext().get(position).setGenre(1);
                                adapter_nextX.notifyDataSetChanged();

                            }
                            else if(nextBean.getType() == 1){

                                for (int i = 0; i <  dataBean.getNext().get(position_data).getNext().size(); i++) {

                                    if (dataBean.getNext().get(position_data).getNext().get(i).getType() == 2){
                                        dataBean.getNext().get(position_data).getNext().get(i).setGenre(0);
                                    }

                                }

                                dataBean.getNext().get(position_data).getNext().get(position).setGenre(1);
                                adapter_nextX.notifyDataSetChanged();

                            }else if(nextBean.getType() == 3){
                                for (int i = 0; i <  dataBean.getNext().get(position_data).getNext().size(); i++) {


                                        dataBean.getNext().get(position_data).getNext().get(i).setGenre(1);

                                }

                                //dataBean.getNext().get(position_data).getNext().get(position).setGenre(1);
                                adapter_nextX.notifyDataSetChanged();
                            }


                            dataBean.getNext().get(position_data).setIsYXZ("已选择");
                            adapter_nextX.notifyDataSetChanged();
                            //dataBean.getNext().get(position_data).getNext().get(position).setGenre(1);
                        }else{
                            dataBean.getNext().get(position_data).getNext().get(position).setGenre(0);
                            boolean flag = true;
                            for (int i = 0; i < dataBean.getNext().get(position_data).getNext().size(); i++) {
                                if (dataBean.getNext().get(position_data).getNext().get(i).getGenre() == 1){
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag) {
                                dataBean.getNext().get(position_data).setIsYXZ("");
                                adapter_nextX.notifyDataSetChanged();
                            }else{

                            }
                        }
                    }
                });
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_ywxq_popuwindow_item;
            }
        };


        adapter_next.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int flag = dataBean.getNext().get(position_data).getNext().get(position).getGenre();

                if (flag == 1){
                    ((CheckBox)view.findViewById(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(false);
                    //dataBean.getNext().get(position_data).getNext().get(position).setGenre(0);
                }else if (flag == 0){
                    ((CheckBox)view.findViewById(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(true);
                    //dataBean.getNext().get(position_data).getNext().get(position).setGenre(1);
                }

                adapter_next.notifyDataSetChanged();
            }
        });
    }

    @OnClick({R.id.ywxq_no_image_fh, R.id.ywxq_no_button_bc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ywxq_no_image_fh:
                finish();
                break;
            case R.id.ywxq_no_button_bc:
                //boolean flag = checkInfo();
                String id_info = "";

                for (int i = 0; i < dataBean.getNext().size(); i++) {
                    id_info = id_info + dataBean.getNext().get(i).getId() + ",";
                    for (int j = 0; j < dataBean.getNext().get(i).getNext().size(); j++) {
                        if (dataBean.getNext().get(i).getNext().get(j).getGenre() == 1){
                            id_info = id_info + dataBean.getNext().get(i).getNext().get(j).getId()+",";
                        }

                    }
                }

                id_info = id_info +""+id;
                requestSubmit(id_info);
                break;
        }
    }

//    private boolean checkInfo() {
//        for (int i = 0; i < dataBean.getNext().size(); i++) {
//            if (TextUtils.isEmpty(businessBean.getData().get(i).getInfo())){
//                DialogUtil.showSimpleDialog(this,"请选择："+businessBean.getData().get(i).getTitle());
//                return false;
//            }
//        }
//        return true;
//    }

    /**
     * 提交保存的数据
     */
    private void requestSubmit(String id_info) {
        HashMap<String,String > map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("users_id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("business_id",id_info);
        map.put("describe",""+ywxqNoEditXgms.getText().toString().trim());

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, URLAddress.URLBASE + URLAddress.URL_YWBQSC, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean bean = (ResultBean) response;
                if (bean.getResult() == 1){
                    // YWGLNOActivity.isVisiable.put(""+title,1);//1,代表显示已经保存
                   // YWGLNOActivity_new.businessBean.getData().get(getIntent().getIntExtra("position",-1)).setGenre(1);
                    finish();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                DialogUtil.showToast(YWXQActivity_save.this,"请勿输入表情等特殊性字符");
            }
        });
    }
}
